<?php 
 
// config 
$m_host = "localhost"; //Host 
$m_user = "teamgobl_cs111"; // User 
$m_pass = "Password23."; // Pass 
$m_db   = "teamgobl_cs111"; // Database
$table  = "web_sessions";
 
$session_expire = 1800; // Session expire time, in seconds (minutes * 60 = seconds) 1800 = 30 minutes

$gc_probability = 100; // Probability that the garbage collection function will be called. 50% chance by default 
 
ini_set("session.gc_probability",$gc_probability); 

session_write_close();
 
/* Open function; Opens/starts session 
 
   Opens a connection to the database and stays open until specifically closed 
   This function is called first and with each page load */ 
 
function open ($s,$n) // do not modify function parameters 
{ 
  global $session_connection, $m_host, $m_user, $m_pass, $m_db; 
  $session_connection = pg_connect("host=$m_host dbname=$m_db user=$m_user password=$m_pass");
  return true; 
} 
 
/* Read function; downloads data from repository to current session 
 
   Queries the database, unencrypts data, and returns it. 
   This function is called after 'open' with each page load. */ 
function read ($id) // do not modify function parameters 
{ 
  global $session_connection,$session_read,$table; 
  $query = "SELECT data FROM $table WHERE id=$1"; 
  $res = pg_query_params($session_connection, $query, array($id)); 
  if(pg_num_rows($res) != 1) return ""; // must return string, not 'false' 
  else 
  { 
    $session_read = pg_fetch_assoc($res); 
    $session_read["data"] = base64_decode($session_read["data"]); 
    return $session_read["data"]; 
  } 
} 
function write ($id,$data) // do not modify function parameters 
{ 
  if(!$data) { return false; } 
  global $session_connection, $session_read, $session_expire, $table; 
  $expire = time() + $session_expire; 
  $data = pg_escape_string(base64_encode($data)); 
  if($session_read) {
      $query = "UPDATE $table SET data=$1, expire=$2 WHERE id=$3"; 
      pg_query_params($session_connection, $query, array($data, $expire, $id));
  } else {
      $query = "INSERT INTO $table VALUES(default, $1, $2, $3);"; 
      pg_query_params($session_connection,$query, array($id, $data, $expire)); 
  }
  return true; 
} 
function close () 
{ 
  global $session_connection; 
  pg_close($session_connection); 
  return true; 
} 
function destroy ($id) // do not modify function parameters 
{ 
  global $session_connection,$table; 
  $query = "DELETE FROM $table WHERE id=$1"; 
  pg_query_params($session_connection,$query,array($id)); 
  return true; 
}
function gc ($expire) 
{ 
  global $session_connection,$table; 
  $query = "DELETE FROM $table WHERE expire < $1"; 
  pg_query_params($session_connection,$query, array(time())); 
}
// Set custom handlers 
session_set_save_handler ("open", "close", "read", "write", "destroy", "gc"); 
 
// Start session 
session_write_close();
session_start(); 

?>